    //
//  Post2ViewController.m
//  SpendFunk
//
//  Created by dongmh on 4/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Post2ViewController.h"
#import "SpendFunkAppDelegate.h"
#import "image.h"
#import "Post1ViewController.h"
#import "Global.h"

@implementation Post2ViewController

- (id)init{

	return self;
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	[self initView];
}

- (void)initView{
	
	NSString *path = nil;
	UIImage *img = nil;
	
	// Header
	path = [[NSString alloc] initWithFormat:@"%@",IMG_HEADER];
	img  = [UIImage imageNamed:path];
	UIImageView *imgvHeader = [[UIImageView alloc] initWithFrame:CGRectMake(0, -20,  img.size.width, img.size.height)];
	[imgvHeader setImage:img];
	[self.view addSubview:imgvHeader];
	[imgvHeader setUserInteractionEnabled:YES];
	[imgvHeader release];
	
	// Back button		
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_BACK];
	img = [UIImage imageNamed:path];	
	m_pBtnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, -14, img.size.width, img.size.height)];
	[m_pBtnBack setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnBack setBackgroundColor:[UIColor clearColor]];
	[m_pBtnBack setTitle:@"Back" forState:UIControlStateNormal];
	m_pBtnBack.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnBack addTarget:nil action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnBack];
	
	/// Done button
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_NEXT];
	img = [UIImage imageNamed:path];	
	m_pBtnDone = [[UIButton alloc] initWithFrame:CGRectMake(320-5-img.size.width, -14, img.size.width, img.size.height)];
	[m_pBtnDone setBackgroundImage:img forState:UIControlStateNormal];	
	[m_pBtnDone setBackgroundColor:[UIColor clearColor]];
	[m_pBtnDone setTitle:@"Done" forState:UIControlStateNormal];
	[m_pBtnDone addTarget:nil action:@selector(onDoneClick) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnDone];
	
	// Background for view
	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45 - 20, img.size.width, img.size.height)];
	[imgvBkgr setImage:img];
	[self.view addSubview:imgvBkgr];
	[imgvBkgr setUserInteractionEnabled:YES];
	[imgvBkgr release];
	
	// Background for addimage
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_ADDIMAGE];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBkgrAddimg = [[UIImageView alloc] initWithFrame:CGRectMake(320/2 - img.size.width/2, 20, img.size.width, img.size.height)];
	[imgvBkgrAddimg setImage:img];
	[imgvBkgr addSubview:imgvBkgrAddimg];
	[imgvBkgrAddimg setUserInteractionEnabled:YES];
	[imgvBkgrAddimg release];
	
	// Add textView
	
	m_pTxtvCaptions = [[UITextView alloc] initWithFrame:CGRectMake(12, 10, 188, 45)];
	m_pTxtvCaptions.delegate = self;
	[imgvBkgrAddimg addSubview:m_pTxtvCaptions];
	//m_pTxtvCaptions.scrollEnabled = NO;
	
	// Add "Addimage" button
	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_TAKEAPHOTO];
	img = [UIImage imageNamed:path];
	//UIImageView *imgvBtnAddImg = [[UIImageView alloc] initWithFrame:CGRectMake(110, 5, 40, 40)];
	m_pBtnAddImage = [[UIButton alloc] initWithFrame:CGRectMake(228, 10, 45, 45)];
	[m_pBtnAddImage setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnAddImage setBackgroundColor:[UIColor clearColor]];
	[m_pBtnAddImage addTarget:nil action:@selector(onClickTakePhoto) forControlEvents:UIControlEventTouchUpInside];
	[imgvBkgrAddimg addSubview:m_pBtnAddImage];
	///
	m_pImgUser = [[UIImageView alloc] init];
	////
	// Background for share
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_SHAREPOST2];
	img = [UIImage imageNamed:path];
	UIImageView *imgvShare = [[UIImageView alloc] initWithFrame:CGRectMake(320/2 - img.size.width/2, 100, img.size.width, img.size.height)];
	[imgvShare setImage:img];
	[imgvShare setUserInteractionEnabled:YES];
	[imgvBkgr addSubview:imgvShare];
	[imgvShare release];
	
	// Switch for share on facebook
	m_pSwtShrFacebook = [[UISwitch alloc] initWithFrame:CGRectMake(200, 10, 20, 20)];
	[imgvShare addSubview:m_pSwtShrFacebook];
	
	m_pSwtShrFriend = [[UISwitch alloc] initWithFrame:CGRectMake(200, 50, 20, 20)];
	[imgvShare addSubview:m_pSwtShrFriend];
	// Please wait ... 
	_blockerView = [[[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 60)] autorelease];
	_blockerView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.8];
	_blockerView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
	_blockerView.alpha = 0.0;
	_blockerView.clipsToBounds = YES;
	if ([_blockerView.layer respondsToSelector: @selector(setCornerRadius:)]) [(id) _blockerView.layer setCornerRadius: 10];
	
	UILabel	*label = [[[UILabel alloc] initWithFrame: CGRectMake(0, 5, _blockerView.bounds.size.width, 15)] autorelease];
	label.text = NSLocalizedString(@"Please Wait…", nil);
	label.backgroundColor = [UIColor clearColor];
	label.textColor = [UIColor whiteColor];
	label.textAlignment = UITextAlignmentCenter;
	label.font = [UIFont boldSystemFontOfSize: 15];
	[_blockerView addSubview: label];
	
	UIActivityIndicatorView				*spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite] autorelease];
	
	spinner.center = CGPointMake(_blockerView.bounds.size.width / 2, _blockerView.bounds.size.height / 2 + 10);
	[_blockerView addSubview: spinner];
	[self.view addSubview: _blockerView];
	[spinner startAnimating];
	
}


-(void)onClickTakePhoto
{
	if(m_pPhotoPreferenceViewCtrl == nil)
	{
		m_pPhotoPreferenceViewCtrl = [[UIImagePickerController alloc] init]; 
		m_pPhotoPreferenceViewCtrl.delegate = self;
		m_pPhotoPreferenceViewCtrl.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	}
	[self presentModalViewController:m_pPhotoPreferenceViewCtrl animated:YES];
}

#pragma mark UITextViewDelegate
-(void)textViewDidEndEditing:(UITextView *)textView
{
    comment = [[NSString alloc] initWithFormat:@"%@",textView.text];
}
#pragma mark imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
	if(image)
	{
		m_pImgUser.image = image;
	}
	[self dismissModalViewControllerAnimated:YES];
	
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[self dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    
    [self dismissModalViewControllerAnimated:YES];
    [picker release];
    
    _image = [image retain];
    
}

 -(void)onBackClick{
	 [g_AppDelegate backToPost1];
	 if (SpendInfo) {
		 [SpendInfo release];
		 SpendInfo = nil;
	 }
 }
- (void)onDoneClick{
	[m_pTxtvCaptions resignFirstResponder];
	if ([m_pTxtvCaptions.text isEqualToString:@""]) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please add text!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	if (SpendInfo&& ![m_pTxtvCaptions.text isEqualToString:@""]) {
		_blockerView.alpha =1.0;
		[self addSpendwithCateid:[SpendInfo valueForKey:kCateID] userid:g_strLoginUserId titleSpend:m_pTxtvCaptions.text amount:[SpendInfo valueForKey:@"kMount"] picture:m_pImgUser.image location:[SpendInfo valueForKey:@"kPlace"]];
	}

}

#pragma mark addspend
- (void)addSpendwithCateid:(NSString*)cateid userid:(NSString*)userid titleSpend:(NSString*)ttle amount:(NSString*)amount picture:(UIImage*)img location:(NSString*)location{
	
	
	
	NSString *post = [[NSString alloc] initWithFormat:@"cate_id=%@&userid=%@&title=%@&amount=%@&picture=%@&location=%@",cateid,userid,ttle,amount,@"",location];
	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	
	NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/spend/addspend"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];  
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
	[theRequest setHTTPBody:postData];	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if( theConnection )
	{
		m_pWebData = [[NSMutableData data] retain];
		
	}
	else
	{
		
	}
}
#pragma mark connect delegate
#pragma mark delegate connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_pWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_pWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect to internet" message:@"Please connect to internet!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	
	[alert release];
	[connection release];
	[m_pWebData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSData *loginStatus = [[NSData alloc] initWithBytes: [m_pWebData mutableBytes] length:[m_pWebData length]];
	
	NSString *a = [[NSString alloc] initWithData:loginStatus encoding:NSUTF8StringEncoding];
	NSLog(@"%@",a);
	
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:loginStatus];
	[xmlParser setDelegate:self];
	
	BOOL success = [xmlParser parse];
	
	if(success)
	{
		_blockerView.alpha =0.0;
		NSLog(@"No Errors");
		//SpendInfo = nil;
		m_pTxtvCaptions.text = nil;
		if (m_pSwtShrFacebook.on == YES) {
			[self displayFacebook];
		}
	}
	else
	{
		NSLog(@"Error Error Error!!!");
	}
	[connection release];
	[m_pWebData release];
}

#pragma mark xmlParser delegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if(!currentElement) 
		currentElement = [[NSString alloc] initWithString:elementName];
	else
		currentElement = [elementName retain];
	
	NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	NSLog(@"Processing Value: %@", string);
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	NSLog(@"%@",elementName);
	
	[currentElementValue release];
	currentElementValue = nil;
}

//////--------------------------FACEBOOK----------------------//
#pragma mark FACEBOOK
-(void)displayFacebook
{
    //logout
    //NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//    NSArray* facebookCookies = [cookies cookiesForURL:
//                                [NSURL URLWithString:@"http://login.facebook.com"]];
//    
//    for (NSHTTPCookie* cookie in facebookCookies) {
//        [cookies deleteCookie:cookie];
//    }
    
    /*Facebook Application ID*/
	NSString *client_id = @"ab7544c6692dd7309d596640027f8ab3";
	
	//alloc and initalize our FbGraph instance
	fbGraph = [[FbGraph alloc] initWithFbClientID:client_id];
	
	//begin the authentication process.....
	[fbGraph authenticateUserWithCallbackObject:self andSelector:@selector(fbGraphCallback:) 
						 andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];
}

#pragma mark -
#pragma mark FbGraph Callback Function
/**
 * This function is called by FbGraph after it's finished the authentication process
 **/
- (void)fbGraphCallback:(id)sender {
	
	if ( (fbGraph.accessToken == nil) || ([fbGraph.accessToken length] == 0) ) {
		
		NSLog(@"You pressed the 'cancel' or 'Dont Allow' button, you are NOT logged into Facebook...I require you to be logged in & approve access before you can do anything useful....");
		
		//restart the authentication process.....
		[fbGraph authenticateUserWithCallbackObject:self andSelector:@selector(fbGraphCallback:) 
							 andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];
		
	} else {
		//login success
        NSLog(@"------------>CONGRATULATIONS<------------, You're logged into Facebook...  Your oAuth token is:  %@", fbGraph.accessToken);
        [self postPictureToFacebook];
	}
	
}

//post picture
-(void)postPictureToFacebook
{
	
	NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:3];
	
	//create a FbGraphFile object insance and set the picture we wish to publish on it
    if (!_image) {
        NSString *path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
        _image = [UIImage imageNamed:path];
        [path release];
    }
	FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:_image];
	
	//finally, set the FbGraphFileobject onto our variables dictionary....
	[variables setObject:graph_file forKey:@"file"];
    
    if (comment == nil) {
        [variables setObject:@"This is my Pic" forKey:@"message"];
    }
	else {
        [variables setObject:comment forKey:@"message"];
    }
    
	
	//the fbGraph object is smart enough to recognize the binary image data inside the FbGraphFile
	//object and treat that is such.....
	[fbGraph doGraphPost:@"me/photos" withPostVars:variables];
	
    UIAlertView *pAlert = [[UIAlertView alloc] initWithTitle:"Message" message:@"Now log into Facebook and look at your profile & photo albums..." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [pAlert show];
    [pAlert release];
	NSLog(@"Now log into Facebook and look at your profile & photo albums...");
	
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
	NSLog(@"Touch begin");
	//UITouch *touch = [[event allTouches] anyObject];
	//CGPoint touchLocation = [touch locationInView:touch.view];  //=> toa do
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"Touch move");
}
- (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"Touch end");
	[m_pTxtvCaptions resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    SAFE_RELEASE(fbGraph);
    SAFE_RELEASE(comment);
    SAFE_RELEASE(_image);
    [super dealloc];
}


@end
